package com.ono;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RequestHelper {
	private final static OkHttpClient CLIENT = new OkHttpClient();
	private final static DecimalFormat TWOPOINT_FORMAT = new DecimalFormat("#.00");
	private String token = "";

	public String getToken() {
		return token;
	}

	public synchronized void setToken(String token) {
		this.token = token;
	}

	public String get(Request request) {
		Response response = null;
		try {
			response = CLIENT.newCall(request).execute();
			if (response.isSuccessful())
				return response.body().string();
			else
				return response.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				response.close();
		}
		return null;
	}

	public boolean download(Request request, String filePath, String fileName) {
		InputStream is = null;
		byte[] buf = new byte[1024];
		int len = 0;
		FileOutputStream fos = null;
		File file = new File(filePath);
		// 储存下载文件的目录
		File dir = file.getParentFile();
		if (!dir.exists())
			dir.mkdirs();
		try {
			Response response = CLIENT.newCall(request).execute();
			is = response.body().byteStream();
			long total = response.body().contentLength();
			System.out.println("==>开始下载:" + fileName + "," + getFileSize(total));
			fos = new FileOutputStream(file);
			long sum = 0;
			while ((len = is.read(buf)) != -1) {
				fos.write(buf, 0, len);
				sum += len;
				int progress = (int) (sum * 1.0f / total * 100);
				// 下载中更新进度条
				System.out.println(fileName + " 已下载：" + progress + "%");
			}
			fos.flush();
			// 下载完成
			System.out.println("<==下载完成：100%," + fileName);
			return true;
		} catch (Exception e) {
			System.err.println("下载失败: " + fileName);
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public Request getRequest(String url) {
		Request request = new Request.Builder().url(url).build();
		return request;
	}

	public Request getAuthorizationRequest(String url) {
		Request request = new Request.Builder().addHeader("Authorization", getToken()).url(url).build();
		return request;
	}

	public static String getFileSize(long size) {
		String fileSize = "";
		if (size > 1024 * 1024) {
			double lenght = size / 1024.0 / 1024.0;
			fileSize = getTwoPointNum(lenght) + "MB";
			return fileSize;
		}
		double lenght = size / 1024.0;
		fileSize = getTwoPointNum(lenght) + "KB";
		return fileSize;
	}

	public static synchronized double getTwoPointNum(double num) {
		String str = TWOPOINT_FORMAT.format(num);
		double temp = Double.valueOf(str);
		return temp;
	}

}
